#include <jni.h>
#include <android/log.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>

static jint fd;

jint ledCtrl(JNIEnv *env, jclass cls, jint which, jint status) {
    int ret = ioctl(fd, status, which);
    __android_log_print(ANDROID_LOG_DEBUG,"LED Demo","native contorl %d", ret);
    return ret;
}

jint ledOpen(JNIEnv *env, jclass cls) {
    fd = open("/dev/leds",O_RDWR);
    __android_log_print(ANDROID_LOG_DEBUG,"LED Demo","native open %d", fd);
    if(fd >= 0)
        return 0;
    else
        return -1;
}

void ledClose(JNIEnv *env, jclass cls) {
    __android_log_print(ANDROID_LOG_DEBUG,"LED Demo","native close");
    close(fd);
}

static const JNINativeMethod methods[] = {
        {"ledCtrl",  "(II)I", (void *) ledCtrl},
        {"ledOpen",  "()I",   (void *) ledOpen},
        {"ledClose", "()V",   (void *) ledClose}
};


JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) {
    JNIEnv *env;
    jclass cls;

    if ((*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6) != JNI_OK) {
        return JNI_ERR;
    }

    cls = (*env)->FindClass(env, "com/demo/hardcontrol/HardControl");
    if(cls==NULL){
        return JNI_ERR;
    }

    if((*env)->RegisterNatives(env, cls, methods, 3) != JNI_OK){
        return JNI_ERR;
    }

    return JNI_VERSION_1_6;
}
